<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog" width="55%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]" size="16" style="margin-right: 5px;"></SvgIcon>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-card shadow="never">
      <el-form ref="formRef"
               v-loading="dataLoading"
               :model="formData"
               :rules="formRules"
               class="full-form"
               label-width="110px">
        <el-row :gutter="12">
          <el-col :md="12">
            <el-form-item label="修改人账号：" prop="modify_account">
              <SelectRemote v-model="formData.modify_account" api-url="/search/user/list" placeholder="输入关键词进行搜索" @change="getUserInfo"/>
            </el-form-item>
          </el-col>

          <el-col :md="12">
            <el-form-item label="邀请人账号：" prop="parent_account">
              <SelectRemote v-model="formData.parent_account" api-url="/search/user/list" placeholder="输入关键词进行搜索" @change="getParentInfo"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div v-if="userData.id > 0 && parentData.id > 0">
        <el-alert v-if="userData.id === parentData.id" :closable="false" center title="修改人和邀请人相同" type="info"/>
        <el-alert v-else-if="parentData.depth_user_ids.indexOf(userData.id) > -1" :closable="false" :title="`修改人: ${userData.account} 是邀请人: ${parentData.account} 的上级`" center type="warning"/>
        <el-alert v-else-if="userData.depth_user_ids.indexOf(parentData.id) > -1" :closable="false" :title="`修改人: ${userData.account} 是邀请人: ${parentData.account} 的粉丝`" center type="error"/>
        <el-alert v-else :closable="false" :title="`修改人: ${userData.account} 和邀请人: ${parentData.account} 没有关系`" center type="success"/>
      </div>
    </el-card>

    <el-row :gutter="12" class="user-info">
      <el-col :md="12">
        <el-card shadow="never">
          <el-descriptions :column="1" title="修改人信息">
            <el-descriptions-item label="编号：" width="100px">
              <span>{{ userData.id }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="账号：" width="100px">
              <span>{{ userData.account }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="昵称：" width="100px">
              <span>{{ userData.nickname }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="层级：" width="100px">
              <span>{{ userData.tier_level }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="邀请人：" width="100px">
              <span>{{ userData.parent_id }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <el-col :md="12">
        <el-card shadow="never">
          <el-descriptions :column="1" title="邀请人信息">
            <el-descriptions-item label="编号：" width="100px">
              <span>{{ parentData.id }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="账号：" width="100px">
              <span>{{ parentData.account }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="昵称：" width="100px">
              <span>{{ parentData.nickname }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="层级：" width="100px">
              <span>{{ parentData.tier_level }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="邀请人：" width="100px">
              <span>{{ parentData.parent_id }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-checkbox v-model="swapModify" border style="margin-right: .8rem">交换位置</el-checkbox>
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-permission="['api:user:modify_parent']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, h, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElMessageBox, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { accountRegex } from '@/utils/validate.ts';
import { defUserInfoData, modifyUserParent, userInfo } from '@/api/api-user.ts';
import { SelectRemote } from '@/components/other';

defineOptions({name: 'parent-modify'})

const formRef = ref<FormInstance>();
const formLoading = ref(false);// 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

// 默认表单数据
let defaultForm = {
  modify_account: undefined,
  parent_account: undefined,
};

// 表单数据
const formData = ref({...defaultForm});
const userData = ref({...defUserInfoData});
const parentData = ref({...defUserInfoData});
const swapModify = ref(false);

// 表单验证规则
const formRules = reactive<FormRules>({
  modify_account: [{required: true, message: '请输入修改者账号', trigger: 'change'}, {pattern: accountRegex, message: '修改者账号格式不正确', trigger: 'blur'}],
  parent_account: [{required: true, message: '请输入邀请人账号', trigger: 'change'}, {pattern: accountRegex, message: '邀请人账号格式不正确', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 打开弹窗 */
const open = async () => {
  dialogMode.value = 2;
  dialogTitle.value = '用户关系';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();
}
// 提供 open 方法，用于打开弹窗
defineExpose({open})

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    ElMessageBox({
      title: '提示',
      message: h('p', null, ['您是否确认进行此操作？ ']),
      type: 'warning',
      showCancelButton: true,
      confirmButtonText: '确认操作',
      cancelButtonText: '取消操作',
    }).then((action) => {
      handleParentModifySubmit();
    });
  });
};

/** 提交请求处理业务 */
const handleParentModifySubmit = () => {
  let params = {
    modify_account: formData.value.modify_account,
    parent_account: formData.value.parent_account,
    swap_modify: swapModify.value
  }
  const loading = ElLoading.service({
    lock: true,
    text: '正在提交中...',
    background: 'rgba(0, 0, 0, 0.2)'
  })
  modifyUserParent(params).then(() => {
    // 提示信息
    ElNotification({title: '成功', message: '修改成功', type: 'success', duration: 2000})
    // 发送操作成功的事件
    emit('refresh')
    // 隐藏窗口
    dialogVisible.value = false
  }).finally(() => loading.close())
};

/** 获取用户信息 */
const getUserInfo = (value: any) => {
  if (value == null || value.id == null) {
    userData.value = {...defUserInfoData}
    return
  }
  userInfo(value.id).then(res => {
    const {info} = res.data;
    userData.value = info;
  })
};

/** 获取邀请人信息 */
const getParentInfo = (value: any) => {
  if (value == null || value.id == null) {
    parentData.value = {...defUserInfoData}
    return
  }
  userInfo(value.id).then(res => {
    const {info} = res.data;
    parentData.value = info;
  })
}

/** 重置表单 */
const handleFormReset = () => {
  // 重置表单数据
  formData.value = {...defaultForm};
  userData.value = {...defUserInfoData};
  parentData.value = {...defUserInfoData};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

</script>

<style lang="scss" scoped>
:deep(.el-descriptions__label) {
  margin-right: 0;
  display: inline-block;
  min-width: 80px;
  vertical-align: top;
  text-align: right;
}

:deep(.el-descriptions__title) {
  border-left: 3px solid var(--el-color-primary);
  padding-left: 10px;
  font-weight: 500;
  font-size: 14px;
  line-height: 16px;
}

.el-checkbox {
  vertical-align: middle;
}

.user-info {
  .el-col {
    margin-top: 12px
  }
}
</style>
